import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { HeroService } from '../hero.service';
@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.sass']
})
export class HeroDetailComponent {
  // @Input()作用???  目前看上去能将prop数据同步更新到父组件
  @Input() hero: Hero = {
    id: 0,
    name: '',
  }
  constructor(
    // 路由信息
    private route: ActivatedRoute,
    private heroService: HeroService,
    private location: Location
  ) { }
  ngOnInit(): void {
    this.getHero();
  }
  getHero(): void {
    // route.snapshot 是一个路由信息的静态快照
    const id = +(this.route.snapshot.paramMap.get('id') || 0);
    this.heroService.getHero(id)
      .subscribe(hero => this.hero = hero);
  }
  goBack(): void {
    this.location.back();
  }
  save(): void {
    this.heroService.updateHero(this.hero)
      .subscribe(() => this.goBack());
  }
}
